const App = {
    mixins: [Save],//配置文件，路径/utils/mixins.js
    data() {
        return {
            Grid: [],
            organization: [],
            personal: [],
            dataForm:{
                Coords:''
            },
            childDataForm: [{ Grid_Member_Type: '1' }],
            childDataForm1: [{}],
            childDataForm2: [{}],
            blue_plate: [],
            cityValue: [],
            cityValue1: [],
            city: [],
            city1: [],
            Parent_Grid_SerialNumber: '',
            house_unit: {},
            is: true,
            ProvinceNumber: ''
        };
    },
    mounted() {
        this.getCategory();
        this.getCity();
        let ls_URL = window.location.href;
        this.ProvinceNumber = getQueryObject(ls_URL, "ProvinceNumber");// 获取 nodeKey 参数
        if (this.action == 'Add') {
            if (this.nodeKey) {
                this.Parent_Grid_SerialNumber = this.nodeKey;
                this.changeParent(this.nodeKey);
            } else if (this.ProvinceNumber) {
                this.cityValue = [this.ProvinceNumber.substring(0, 2) + '0000', this.ProvinceNumber.substring(0, 4) + '00', this.ProvinceNumber.substring(0, 6)]
                this.changeCity(this.cityValue)
                this.cityValue1 = [this.ProvinceNumber.substring(0, 9), this.ProvinceNumber];
                this.changeCity1(this.cityValue1)
            } else {
                this.cityValue = ['230000', '232700', '232723']
                this.changeCity(this.cityValue)
            }
        }
    },
    watch: {
        'dataForm.Grid_SerialNumber'(val) {
            if (this.action == 'Modify' && this.is) {
                this.is = false;
                let str = this.dataForm.Parent_Grid_SerialNumber
                if (str.includes('GI')) {
                    this.Parent_Grid_SerialNumber = str
                }else if (str.substring(0, 6)) {
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${mh}/clientOperation/getDistrictTree`,
                        type: "GET",
                        data: {
                            DistrictCode: str.substring(0, 6)
                        },
                        success: (data) => {
                            console.log(data);
                            if (data.length == 1) {
                                this.city1 = data[0].children;
                                this.cityValue1 = [str.substring(0, 9), str];
                                this.cityValue = [str.substring(0, 2) + '0000', str.substring(0, 4) + '00', str.substring(0, 6)]
                            }
                        },
                        complete: (XMLHttpRequest) => {
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json",
                    });
                }
            }
        },
        childDataForm2: {
            handler(val) {
                if (val.length > 0) {
                    let str = "";
                    val.forEach(item => {
                        if (str) {
                            str += "\r\nOR Blue_Plate_SerialNumber='" + item.Blue_Plate_SerialNumber + "'"
                        } else {
                            str = "Blue_Plate_SerialNumber='" + item.Blue_Plate_SerialNumber + "'"
                        }
                    })

                    $.ajax({
                        headers: requestHeaders(),
                        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                        type: "POST",
                        data: {
                            Data: 'blue_plate_house_unit',
                            Condition: "Row_Status='0' AND (" + str + ")",
                        },
                        success: (data) => {
                            data.forEach(item => {
                                if (this.house_unit[item.Blue_Plate_SerialNumber]) {
                                    this.house_unit[item.Blue_Plate_SerialNumber].push(item);
                                } else {
                                    this.house_unit[item.Blue_Plate_SerialNumber] = [item];
                                }
                            })
                            console.log(this.house_unit);
                        },
                        complete: (XMLHttpRequest) => {
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json",
                    });
                    console.log(val);
                }
            },
            deep: true
        }
    },
    methods: {
        PH_Validity(rule, value, callback) {
            if (!value) {
                callback(new Error('请输入联系电话'));
            } else if (!validatemobile(value)) {
                callback(new Error('联系电话格式不正确'));
            } else {
                callback();
            }
        },
        InputCoords(val) {
            // if (this.action == 'Modify') {
            //     return false;
            // }
            this.dataForm.Coords = val.replace(/\s+/g, '');
            const coordRegex = /^\[\[-?\d+\.?\d*,\s*-?\d+\.?\d*\]+(,\[-?\d+\.?\d*,\s*-?\d+\.?\d*\])*\]$/;
            if (!coordRegex.test(val)) {
                return false;
            }
            try {
                const coordinates = JSON.parse(val);

                if (!Array.isArray(coordinates)) {
                    return false;
                }

                for (const point of coordinates) {
                    if (!Array.isArray(point) || point.length !== 2) {
                        return false;
                    }

                    for (const coord of point) {
                        if (typeof coord !== 'number' && isNaN(parseFloat(coord))) {
                            return false;
                        }
                    }
                }
                $.ajax({
                    url: `${y}/getBluePlateAsCoordsAction`,
                    type: "POST",
                    data: {
                        Data: val
                    },
                    success: ({ Status, Data }) => {
                        if (Status == 'success' && Data.length > 0) {
                            this.childDataForm2 = [];
                            Data.forEach(item => {
                                this.childDataForm2.push({
                                    Blue_Plate_SerialNumber: item.Blue_Plate_SerialNumber
                                })
                            })
                        }  else {
                            this.$message({
                                type: 'warning',
                                message: '暂无未关联的蓝牌，请前往添加蓝牌'
                            });
                        }
                    },
                    dataType: "json",
                });
            } catch (e) {
                return false;
            }

        },
        changeParent(val) {
            if (val) {
                this.cityValue = [];
                this.cityValue1 = [];
                let obj = this.Grid.filter(i=>i.Grid_SerialNumber == val)[0];
                if (obj) {
                    this.dataForm.Province_Number = obj.Province_Number;
                    this.dataForm.City_Number = obj.City_Number;
                    this.dataForm.County_Nubmer = obj.County_Nubmer;
                    this.dataForm.Town_Number = obj.Town_Number;
                    this.dataForm.Village_Number = obj.Village_Number;
                }
                this.dataForm.Parent_Grid_SerialNumber = val
            }
        },
        changeCity1(val) {
            if (val.length > 0) {
                this.dataForm.Town_Number = val[0];
                this.dataForm.Village_Number = val[1];
                this.dataForm.Parent_Grid_SerialNumber = val[1];
            } else {
                this.dataForm.Parent_Grid_SerialNumber = '';
            }

        },
        handleChange(val, row) {
            if (val) {
                let obj = this.personal.filter(i => i.ID_Card_Number == val)[0];
                if (obj) {
                    row.Contact_Phone = obj.Contact_Phone;
                }
            }
        },
        changeCity(val) {
            if (val.length > 0) {
                this.dataForm.Province_Number = val[0];
                this.dataForm.City_Number = val[1];
                this.dataForm.County_Nubmer = val[2];
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/clientOperation/getDistrictTree`,
                    type: "GET",
                    data: {
                        DistrictCode: val[2]
                    },
                    success: (data) => {
                        this.city1 = data[0].children;
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json",
                });
            }
        },
        getCity() {
            $.ajax({
                url: `${absolutepath()}api/Districtjl.json`,
                method: "get",
                success: (data) => {
                    data.forEach(item => {
                        item.children.forEach(ite => {
                            ite.children.forEach(it => {
                                it.children = undefined
                            })
                        })
                    })
                    this.city = data;
                }
            });
        },
        getCategory() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'grid_information',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.Grid = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'personal_information',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.personal = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
                method: "post",
                data: {
                    SQLSerialNumber: 'f_blue_plate_information2',
                    Condition: '',
                    ExtensionCondition:  '',
                },
                success: (data) => {
                    // window.btoa(unescape(encodeURIComponent("AND blue_plate_information.isSelect = '0'")))
                    if (data.length > 0) {
                        data.forEach(item=>{
                            item.label = '蓝牌名称: '+ item.Blue_Plate_Name 
                      + ' | 蓝牌编号:'+ item.Blue_Plate_SerialNumber 
                      + ' | 共' + item.Unit_Quantity + '个单元 | '
                      +item.Layer_Quantity + '层 | 每层'
                      +item.Room_Quantity + '户'
                        })
                        console.log(data);
                        this.blue_plate = data; // 直接使用 this
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '暂无未关联的蓝牌，请前往添加蓝牌'
                        });
                    }
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
                type: "GET",
                data: {
                    TableName: 'government_agencies',
                    NodeCode: "",
                },
                success: (data) => {
                    this.organization = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));
                let ls_MainTableName = lJSONObject_Data_Options.TableName;
                let ls_DataForm = lJSONObject_Data_Options.form;
                let ls_primary_key = lJSONObject_Data_Options.primary_key;
                let grid_blue_plate_log = [];
                if (this[ls_DataForm].Parent_Grid_SerialNumber) {
                    let obj = this.Grid.filter(i => i.Grid_SerialNumber == this[ls_DataForm].Parent_Grid_SerialNumber)[0];
                    if (obj) {
                        this[ls_DataForm].Grid_Level = accAdd(obj.Grid_Level, 1);
                    } else {
                        this[ls_DataForm].Grid_Level = 1
                    }

                } else {
                    this[ls_DataForm].Grid_Level = 1
                }
                //没有子表下面内容就会报错，try/catch抛出异常
                try {
                    //可能涉及多个子表
                    document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                        let lJSONObject_ChildData_Options = new Object();
                        lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                        let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                        let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                        // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                        if (this[ls_DataForm][ls_primary_key]) {
                            this[ls_ChildDataForm].forEach(item => {
                                item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
                            })
                        }
                        //建立子表结构体
                        let JSONArray_ChildRecord = new Array();
                        JSONArray_ChildRecord = this[ls_ChildDataForm];
                        if (!this[ls_DataForm].Children) {
                            this[ls_DataForm].Children = new Object();
                        }
                        this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
                    })
                } catch (error) {

                }
                //建立新增提交结构
                let lJSONObject_DataSet = new Object();
                if (action == 'Add') {
                    if (this.nodeKey) {
                        this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
                    }
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(this[ls_DataForm]);
                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    lJSONObject_DataSet[action] = lJSONObject_Table;
                } else if (action == 'Modify') {
                    const { add, modify } = this.deal(this[ls_DataForm]);
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(modify);

                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

                    lJSONObject_DataSet[action] = lJSONObject_Table;

                    if (modify.Children && modify.Children.grid_member) {
                        modify.Children.grid_member.forEach(item => {
                            if (item.Personal_SerialNumber != item.Personal_SerialNumber_Original) {
                                grid_blue_plate_log.push({
                                    Grid_Member_SerialNumber: item.Grid_Member_SerialNumber,
                                    Grid_Member_Personal_SerialNumber: item.Personal_SerialNumber,
                                    Personal_SerialNumber: item.Personal_SerialNumber_Original
                                })
                            }
                        })
                    }


                    if (add != null) {
                        let lJSONArray_Record_Add = new Array();
                        lJSONArray_Record_Add.push(add);

                        let lJSONObject_Table_Add = new Object();
                        lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

                        lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
                    }
                }
                if (!lJSONObject_DataSet['Add']) {
                    lJSONObject_DataSet['Add'] = new Object();
                }
                if (!lJSONObject_DataSet['Modify']) {
                    lJSONObject_DataSet['Modify'] = new Object();
                }
                let blue_plate_house_unit = [];
                for (let key in this.house_unit) {
                    this.house_unit[key].forEach(item => {
                        if (item.Responsible_Person != item.Responsible_Person_Original) {
                            blue_plate_house_unit.push(item);
                            grid_blue_plate_log.push({
                                House_Unit_SerialNumber: item.House_Unit_SerialNumber,
                                House_Unit_Personal_SerialNumber: item.Responsible_Person,
                                Personal_SerialNumber: item.Responsible_Person_Original
                            })
                        }
                    })
                }
                lJSONObject_DataSet['Add']['grid_blue_plate_log'] = grid_blue_plate_log;
                lJSONObject_DataSet['Modify']['blue_plate_house_unit'] = blue_plate_house_unit;
               
                let str = this.childDataForm2.map(i=>"'" + i.Blue_Plate_SerialNumber + "'").join(",");
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                    method: "post",
                    data: {
                        Data: 'blue_plate_information',
                        Condition: `Blue_Plate_SerialNumber IN (${str ? str : "''"})`,
                    },
                    success: (data) => {
                        data.forEach(item=>{
                            let obj = this.childDataForm2.filter(i=>i.Blue_Plate_SerialNumber == item.Blue_Plate_SerialNumber)[0];
                            if (obj && obj.Row_Status != '1') {
                                item.isSelect = '1'
                            } else {
                                item.isSelect = '0'
                            }
                        })
                        lJSONObject_DataSet['Modify']['blue_plate_information'] = data;
                        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                        if (!lJSONObject_DataSet['Add']) {
                            lJSONObject_DataSet['Add'] = new Object();
                        }
                        lJSONObject_DataSet['Add']['base_operation_log'] = [{
                            Operation_Type: '0',
                            Operation_Path: this.relativePath,
                            Operation_Main,
                            Operation_Interface: "generalSaveByRequestBody",
                            Operation_IP: getIpAddress()
                        }]
                        submitSave(lJSONObject_DataSet,(res)=>{
                            if (res.Status == 'success') {
                                this.loading = false;
                                window.location.href = './index.html'
                                // window.history.go(-1);
                            }
                        })
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest)
                    },
                });
               
                // $.ajax({
                //     headers: requestHeaders("JSON"),
                //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                //     method: "post",
                //     data: JSON.stringify({
                //         Data: lJSONObject_DataSet,
                //     }),
                //     success: (res) => {
                //         if (res.Status == 'success') {
                //             window.location.href = './index.html'
                //             // window.history.go(-1);
                //         }
                //     },
                //     complete: (XMLHttpRequest) => {
                //         requestPretreatment(XMLHttpRequest);
                //     },
                // });
            }

        },
    },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-select',ylSelect)
app.component('yl-upload', ylUpload);
app.component('yl-text-editor', ylTextEditor);
app.component('yl-cascader', ylCascader);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
